package pairwise_model;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.StringTokenizer;

public class Pairwise_Cosine {
	public HashMap<String,Integer> wordindex = new HashMap<String,Integer>();
	public List<String> words = new ArrayList<String>();
	public int wordcount = 0;
	public double BuildProfile(String doc, String doc2)
	{
		StringTokenizer st = new StringTokenizer(doc);
		while(st.hasMoreTokens())
		{
			String token = st.nextToken().toLowerCase();
			if(! wordindex.containsKey(token) && !token.contains("cold"))
			{
				wordindex.put(token, wordcount++);
				words.add(token);
			}
		}
		st = new StringTokenizer(doc2);
		while(st.hasMoreTokens())
		{
			String token = st.nextToken().toLowerCase();
			if(! wordindex.containsKey(token)&& !token.contains("cold"))
			{
				wordindex.put(token, wordcount++);
				words.add(token);
			}
		}
		int arr1[] = new int[wordcount];
		int arr2[] = new int[wordcount];
		st = new StringTokenizer(doc);
		while(st.hasMoreTokens())
		{
			String token = st.nextToken().toLowerCase();
			if(!token.contains("cold")){
			int index = wordindex.get(token);
			arr1[index]++;}
		}
		st = new StringTokenizer(doc2);
		while(st.hasMoreTokens())
		{
			String token = st.nextToken().toLowerCase();
			if(!token.contains("cold")){
			int index = wordindex.get(token);
			arr2[index]++;}
		}
		double cosine = 0.0;
		cosine = ComputeCosine(arr1, arr2);
		return cosine;
	}
	public double ComputeCosine(int matrix1[],int matrix2[])
	{
		double cosine = 0.0;
		double sum = 0.0;
		double square1 = 0.0, square2 = 0.0;
		for(int i=0;i<wordcount;i++)
		{
			sum += matrix1[i]*matrix2[i];
			square1 += matrix1[i]*matrix1[i];
			square2 += matrix2[i]*matrix2[i];
		}
		square1 = Math.sqrt(square1);
		square2 = Math.sqrt(square2);
		cosine = sum / (square1 * square2);
		cosine = cosine>1.0? 1.0 : cosine;
		return cosine;
	}

}
